package com.sc.social;

import com.sc.security.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.social.config.annotation.EnableSocial;
import org.springframework.social.config.annotation.SocialConfigurerAdapter;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.ConnectionSignUp;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.connect.jdbc.JdbcUsersConnectionRepository;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.social.security.SpringSocialConfigurer;

import javax.sql.DataSource;

/**
 * @author sc
 * Created on  2018/1/18
 */
@Configuration
@EnableSocial
public class SocialConfig extends SocialConfigurerAdapter {
    @Autowired
    private DataSource dataSource;
    @Autowired
    private SecurityProperties securityProperties;
    @Autowired
    private ConnectionFactoryLocator factoryLocator;
    @Autowired(required = false)
    private ConnectionSignUp demoConnectionSignUp;
    @Autowired(required = false)
    private SocialAuthFilterPostProcessor socialAuthFilterPostProcessor;
    @Override
    public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
        JdbcUsersConnectionRepository jdbcUsersConnectionRepository = new JdbcUsersConnectionRepository(dataSource, connectionFactoryLocator, Encryptors.noOpText());
        if(demoConnectionSignUp!=null){
            jdbcUsersConnectionRepository.setConnectionSignUp(demoConnectionSignUp);
        }
        return jdbcUsersConnectionRepository;
    }


    @Bean
    public SpringSocialConfigurer mySocialSecurityConfig(){

        MySpringSocialConfig mySpringSocialConfig = new MySpringSocialConfig(securityProperties.getSocial().getFilterProcessUrl());
        mySpringSocialConfig.setSocialAuthFilterPostProcessor(socialAuthFilterPostProcessor);
        mySpringSocialConfig.signupUrl(securityProperties.getBrowser().getSignUpUrl());
        return mySpringSocialConfig;
    }

    @Bean
    public ProviderSignInUtils providerSignInUtils(){
        return new ProviderSignInUtils(factoryLocator,getUsersConnectionRepository(factoryLocator));
    }
}
